<template>
  <view class="media-transcriber">
    <view class="upload-section">
      <!-- 如果没有传入 videoSrc，则显示文件输入 -->
      <input
        v-if="!videoSrc"
        type="file"
        ref="fileInput"
        accept="audio/*,video/*"
        @change="handleFileChange"
      />
      <button
	    class="AA"
        :disabled="(!selectedFile && !videoSrc) || isTranscribing"
        @click="transcribeMedia"
      >
        {{ isTranscribing ? '处理中...' : '开始转录' }}
      </button>
    </view>
    <view class="result-section" v-if="transcription">
      <text>转录结果:</text>
      <view class="markdown-content" v-html="parsedTranscription"></view>
    </view>
    <view class="error-section" v-if="error">
      <text class="error">{{ error }}</text>
    </view>
  </view>
</template>

<script lang="uts">
  import { defineComponent } from 'vue'
  import axios from 'axios'
  import { marked } from 'marked'

  export default defineComponent({
    props: {
      videoSrc: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        selectedFile: null as File | null,
        isTranscribing: false,
        transcription: '',
        parsedTranscription: '',
        error: ''
      }
    },
    watch: {
      async transcription(newValue) {
        if (newValue) {
          this.parsedTranscription = await marked.parse(newValue);
        } else {
          this.parsedTranscription = '';
        }
      }
    },
    methods: {
      handleFileChange(event: any) {
        this.selectedFile = event.target.files[0]
        this.transcription = ''
        this.error = ''
      },
      async transcribeMedia() {
        let fileToTranscribe: string | File | null = null;

        if (this.videoSrc) {
          fileToTranscribe = this.videoSrc;
        } else if (this.selectedFile) {
          fileToTranscribe = this.selectedFile;
        } else {
          this.error = '请先选择一个音频或视频文件或提供视频路径';
          console.error('No file selected');
          return;
        }

        this.isTranscribing = true;
        this.error = '';
        this.transcription = '';

        const formData = new FormData();
        try {
          if (typeof fileToTranscribe === 'string') {
            console.log('Fetching video from:', fileToTranscribe);
            const response = await fetch(fileToTranscribe);
            if (!response) {
              throw new Error('Fetch failed: No response received');
            }
            if (!response.ok) {
              throw new Error(`Fetch failed: ${response.status} ${response.statusText}`);
            }
            const blob = await response.blob();
            const fileName = fileToTranscribe.split('/').pop() || 'media_file.mp4';
            console.log('Appending blob:', fileName, blob.size, 'bytes');
            formData.append('file', blob, fileName);
          } else {
            if (fileToTranscribe) {
              console.log('Appending file:', fileToTranscribe.name, fileToTranscribe.size, 'bytes');
              formData.append('file', fileToTranscribe);
            }
          }
          formData.append('output_file', 'transcription_result.txt');
          console.log('FormData prepared, sending request...');

          const response = await axios.post('http://localhost:5000/transcribe', formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            },
            timeout: 30000000 // 5 分钟超时
          });

          console.log('Server response:', response.data);
          if (response.data.status === 'success') {
            this.transcription = response.data.processed_text;
          } else {
            this.error = response.data.error || '转录失败';
            console.error('Transcription failed:', response.data.error);
          }
        } catch (err: any) {
          console.error('Request error:', err);
          if (err.response) {
            this.error = err.response.data?.error || `请求失败: ${err.response.status} ${err.response.statusText}`;
            console.error('Response details:', err.response.data);
          } else if (err.request) {
            this.error = '请求失败: 无法连接到服务器，请检查服务器状态';
            console.error('No response received');
          } else {
            this.error = `请求失败: ${err.message}`;
            console.error('Error details:', err.message);
          }
        } finally {
          this.isTranscribing = false;
        }
      }
    }
  })
</script>

<style>
  .media-transcriber {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    padding: 20rpx;
    box-sizing: border-box;
  }
  .upload-section {
    margin-bottom: 20rpx;
    display: flex;
    flex-direction: row;
    align-items: center;
    gap: 20rpx;
    flex-shrink: 0;
  }
  input[type="file"] {
    margin-right: 10rpx;
  }
  button {
    padding: 8rpx 16rpx;
    background-color: #007bff;
    color: white;
    border: none;
    border-radius: 2px;
  }
  .AA {
	  width: 90px;
	  height: 30px;
	  display: flex;
	  align-items: center;
	  justify-content: center;
  }
  button:disabled {
    background-color: #cccccc;
  }
  .result-section {
    flex: 1;
    overflow-y: auto;
    margin-top: 20rpx;
  }
  .result-section text {
    display: block;
    margin-bottom: 10rpx;
    font-weight: bold;
  }
  .markdown-content {
    background-color: #f8f9fa;
    padding: 10rpx;
    border-radius: 4rpx;
    word-wrap: break-word;
  }
  .markdown-content p {
    margin: 0 0 10rpx 0;
  }
  .markdown-content ul,
  .markdown-content ol {
    margin: 0 0 10rpx 20rpx;
    padding: 0;
  }
  .markdown-content li {
    margin-bottom: 5rpx;
  }
  .markdown-content h1,
  .markdown-content h2,
  .markdown-content h3,
  .markdown-content h4,
  .markdown-content h5,
  .markdown-content h6 {
    margin: 10rpx 0;
    font-weight: bold;
  }
  .markdown-content code {
    background-color: #e9ecef;
    padding: 2rpx 4rpx;
    border-radius: 4rpx;
  }
  .markdown-content pre {
    background-color: #e9ecef;
    padding: 10rpx;
    border-radius: 4rpx;
    overflow-x: auto;
  }
  .error-section {
    margin-top: 20rpx;
    flex-shrink: 0;
  }
  .error {
    color: red;
    background-color: #f8f9fa;
    padding: 10rpx;
    border-radius: 4rpx;
  }
</style>